package com.ts.api.http.receive.biz;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.reflection.CopyUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.http.receive.entity.apply.req.ApiReceiveApplyChengXiaoHuaV2;
import com.ts.api.http.receive.entity.dataexchange.req.ApiReceiveDataExchangeChengXiaoHuaV2;
import com.ts.api.module.api.convert.core.annotation.ApiReceive;
import com.ts.api.module.api.convert.core.annotation.ApiReceiveConvertType;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveApply;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveDecrypt;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveNotice;
import com.ts.api.module.api.convert.receive.entity.ApiReceivePhoneMd5DataExchange;
import com.ts.api.module.api.convert.receive.handler.ApiReceivePhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiUserRequest;

import java.util.Map;

/**
 * 诚小花
 *
 * https://apifox.com/apidoc/shared-d5b24b28-6fe4-4e40-b1ec-0770b7d997d2
 *
 * @author WJB
 */
@ApiReceive(apiClientId = "1928484659004329984",type = ApiReceiveConvertType.API_CHANNEL_PHONE_MD5)
public class ApiReceivePhoneMd5ChengXiaoHuaV2 implements ApiReceivePhoneMd5ConvertHandler {

    private static String KEY = "123456789abcdefg";

    @Override
    public Map<String, String> requireParam(RequestVO requestVO) throws Exception {
        return null;
    }

    @Override
    public ApiReceiveDecrypt decrypt(Map<String, String> paramMap, RequestVO requestVO) throws Exception {
        String body = requestVO.getBody();
        return new ApiReceiveDecrypt(body);
    }

    @Override
    public ApiUserRequest parseDataExchange(ApiReceiveDecrypt apiReceiveDecrypt) throws Exception {
        ApiReceiveDataExchangeChengXiaoHuaV2 parse = apiReceiveDecrypt.parse(ApiReceiveDataExchangeChengXiaoHuaV2.class);
        {
            AES ecb = AES.createEcb(KEY.getBytes());
            // 姓名解密
            String name = parse.getUserName();
            String decryptname = ecb.decryptFromBase64Str(name);
            parse.setUserName(decryptname);
            //身份证号解密
            String idcard = parse.getIdcard();
            if (ValidParam.isNotEmpty(idcard)) {
                String decryptidcard = ecb.decryptFromBase64Str(idcard);
                parse.setIdcard(decryptidcard);
            }
        }
        ApiUserRequest apiUserRequest = CopyUtils.copy(parse, ApiUserRequest.class);
        fieldMapping(apiUserRequest);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> respDataExchange(ApiReceivePhoneMd5DataExchange dataExchangeMessage) throws Exception {
        boolean suc = dataExchangeMessage.hasBizSuc();

        // 失败
        if (!suc) {
            Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
            resultMap.put("code", "500");
            resultMap.put("desc", dataExchangeMessage.getBizMsg());
            return resultMap;
        }

        //成功
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        resultMap.put("code", "0000");
        resultMap.put("desc", "SUCCESS");
        resultMap.put("data", MapUtils.newLinkedHashMap(dataMap -> {
            //  产品原本价格（CPS分润模式必须返回价格）CPA模式无价格返回
            dataMap.put("price", dataExchangeMessage.getPrice());
            //  机构名称
            dataMap.put("companyName", dataExchangeMessage.getOrgName());
            //  产品logo
            dataMap.put("logoUrl", dataExchangeMessage.getLogoPath());
            //  产品名称
            dataMap.put("productName", dataExchangeMessage.getDisplayName());
            //  url
            dataMap.put("checkUrl", dataExchangeMessage.getCallUrl());
            //  协议集合
            dataMap.put("protocolList", CollUtils.newArrayList(newList -> {
                Map<String, Object> protocol = MapUtils.newLinkedHashMap();
                protocol.put("protocolName", "个人信息授权协议");
                protocol.put("protocolUrl", "https://axh.rongyiudai.com/h5ViewProtocol?uniqueCode=1fc1379861b34ef0898d7864c33b18e2");
                newList.add(protocol);
            }));
        }));
        return resultMap;
    }

    @Override
    public ApiUserRequest parseApply(ApiReceiveDecrypt apiReceiveDecrypt) throws Exception {
        ApiReceiveApplyChengXiaoHuaV2 parse = apiReceiveDecrypt.parse(ApiReceiveApplyChengXiaoHuaV2.class);
        {
            // 手机号解密
            String phone = parse.getPhone();
            AES cbc = AES.createEcb(KEY.getBytes());
            String decryptphone = cbc.decryptFromBase64Str(phone);
            parse.setPhone(decryptphone);

            // 姓名解密
            String name = parse.getUserName();
            String decryptname = cbc.decryptFromBase64Str(name);
            parse.setUserName(decryptname);

            //身份证号解密
            String idcard = parse.getIdcard();
            if (ValidParam.isNotEmpty(idcard)) {
                String decryptidcard = cbc.decryptFromBase64Str(idcard);
                parse.setIdcard(decryptidcard);
            }
        }
        ApiUserRequest apiUserRequest = CopyUtils.copy(parse, ApiUserRequest.class);
        fieldMapping(apiUserRequest);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> respApply(ApiReceiveApply applyMessage) throws Exception {
        boolean suc = applyMessage.hasBizSuc();

        // 失败
        if (!suc) {
            Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
            resultMap.put("code", "500");
            resultMap.put("msg", applyMessage.getBizMsg());
            return resultMap;
        }

        // 成功
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        resultMap.put("code", "0000");
        resultMap.put("desc", "SUCCESS");
        return resultMap;
    }

    @Override
    public void fieldMapping(ApiUserRequest apiUserRequest) {

        // 额度
        //10000 -（1万以下）
        //50000 -（1-2万）
        //100000 - （3万以上）
        // loanAmount 贷款金额
        // 1 3万以下
        // 2 5万-10万
        // 3 10万-20万
        // 4 20万以上
        String loanAmount = apiUserRequest.getLoanAmount();
        if (ValidParam.isNotEmpty(loanAmount)) {
            String text = ChooseEq.create()
                    .when(loanAmount, "10000", "1")
                    .when(loanAmount, "50000", "1")
                    .when(loanAmount, "100000", "2")
                    .end();
            apiUserRequest.setLoanAmount(text);
        }

        // sex 性别（1男 2女）
        // sex 性别
        // 0 男
        // 1 女
        // 2 未知
        String sex = apiUserRequest.getSex();
        if (ValidParam.isNotEmpty(sex)) {
            String sexChoose = ChooseEq.create()
                    .when(sex, "1", "0")
                    .when(sex, "2", "1")
                    .end("2");
            apiUserRequest.setSex(sexChoose);
        }

        // sesameId 芝麻分(1：大于700，2：650-700 3：600-650，4：小于600)
        // sesameCredit 芝麻分
        // 1 600分以下
        // 2 600~649分
        // 3 650~699分
        // 4 700分以上
        String sesameCredit = apiUserRequest.getSesameCredit();
        if (ValidParam.isNotEmpty(sesameCredit)) {
            String value = ChooseEq.create()
                    .when(sesameCredit, "1", "4")
                    .when(sesameCredit, "2", "3")
                    .when(sesameCredit, "3", "2")
                    .when(sesameCredit, "4", "1")
                    .end();
            apiUserRequest.setSesameCredit(value);
        }

        // vehicleId 车(车 1-有 0-无)
        // carInfo 车辆情况
        // 1 无车产
        // 2 有车不抵押
        // 3 有车可抵押
        // 4 有车产
        String carInfo = apiUserRequest.getCarInfo();
        if (ValidParam.isNotEmpty(carInfo)) {
            String value = ChooseEq.create()
                    .when(carInfo, "1", "4")
                    .when(carInfo, "0", "1")
                    .end();
            apiUserRequest.setCarInfo(value);
        }

        // houseId 房(房 1-有 0-无)
        // realEstateInfo 房产情况
        // 1 无房产
        // 2 有房不抵押
        // 3 有房可抵押
        // 4 有房产
        // 5 有按揭房产
        // 6 有全款房产
        String realEstateInfo = apiUserRequest.getRealEstateInfo();
        if (ValidParam.isNotEmpty(realEstateInfo)) {
            String value = ChooseEq.create()
                    .when(realEstateInfo, "1", "4")
                    .when(realEstateInfo, "0", "1")
                    .end();
            apiUserRequest.setRealEstateInfo(value);
        }

        // socialId 社保(社保 1-有 0-无)
        // socialSecurity 社保缴纳
        // 1 无社保
        // 2 缴纳6个月以下
        // 3 缴纳6个月以上
        // 4 有社保
        String socialSecurity = apiUserRequest.getSocialSecurity();
        if (ValidParam.isNotEmpty(socialSecurity)) {
            String value = ChooseEq.create()
                    .when(socialSecurity, "1", "4")
                    .when(socialSecurity, "0", "1")
                    .end();
            apiUserRequest.setSocialSecurity(value);
        }

        // accumulation 公积金(公积金 1-有 0-无)
        // providentFund 公积金
        // 1 无公积金
        // 2 缴纳6个月以下
        // 3 缴纳6个月以上
        // 4 有公积金
        String providentFund = apiUserRequest.getProvidentFund();
        if (ValidParam.isNotEmpty(providentFund)) {
            String value = ChooseEq.create()
                    .when(providentFund, "1", "4")
                    .when(providentFund, "0", "1")
                    .end();
            apiUserRequest.setProvidentFund(value);
        }

        // insureId 保险(保单 1-有 0-无)
        // insurancePolicy 保险保单
        // 1 无保险保单
        // 2 缴纳未满1年
        // 3 缴纳1年以上
        // 4 有保险保单
        String insurancePolicy = apiUserRequest.getInsurancePolicy();
        if (ValidParam.isNotEmpty(insurancePolicy)) {
            String value = ChooseEq.create()
                    .when(insurancePolicy, "1", "4")
                    .when(insurancePolicy, "0", "1")
                    .end();
            apiUserRequest.setInsurancePolicy(value);
        }

        // business 营业执照 1-有 0-无
        // 营业执照注册年限
        // 1 未注册
        // 2 注册1年以下
        // 3 注册1~5年
        // 4 注册5年以上
        String bizLicenseYear = apiUserRequest.getBizLicenseYear();
        if (ValidParam.isNotEmpty(bizLicenseYear)) {
            String value = ChooseEq.create()
                    .when(bizLicenseYear, "1", "2")
                    .when(bizLicenseYear, "0", "1")
                    .end();
            apiUserRequest.setBizLicenseYear(value);
        }

        // baitiao 白条 1-有 0-无
        // btlimit 白条
        // 1 无额度
        // 2 3千以下
        String baitiao = apiUserRequest.getBtLimit();
        if (ValidParam.isNotEmpty(baitiao)) {
            String value = ChooseEq.create()
                    .when(baitiao, "1", "2")
                    .when(baitiao, "0", "1")
                    .end();
            apiUserRequest.setBtLimit(value);
        }

        // baitiao 花呗 1-有 0-无
        // btlimit 花呗
        // 1 无额度
        // 2 3千以下
        String huabei = apiUserRequest.getHbLimit();
        if (ValidParam.isNotEmpty(huabei)) {
            String value = ChooseEq.create()
                    .when(huabei, "1", "2")
                    .when(huabei, "0", "1")
                    .end();
            apiUserRequest.setHbLimit(value);
        }

        // baitiao 信用卡 1-有 0-无
        // btlimit 信用卡
        // 1 无信用卡
        // 2 3千以下
        String credit = apiUserRequest.getCreditLimit();
        if (ValidParam.isNotEmpty(credit)) {
            String value = ChooseEq.create()
                    .when(credit, "1", "2")
                    .when(credit, "0", "1")
                    .end();
            apiUserRequest.setCreditLimit(value);
        }

        // overdueId 信用情况(6个月内逾期 1-有 0-无)
        // overdue 逾期
        // 1 无逾期
        // 2 当前有逾期
        // 3 一年以内无逾期
        String overdue = apiUserRequest.getOverdue();
        if (ValidParam.isNotEmpty(overdue)) {
            String value = ChooseEq.create()
                    .when(overdue, "0", "1")
                    .when(overdue, "1", "2")
                    .end();
            apiUserRequest.setOverdue(value);
        }
    }


    @Override
    public Object reqPullApplyNotice(ApiReceiveNotice apiReceiveNotice) {
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        resultMap.put("phoneMd5", apiReceiveNotice.getPhoneMd5());
        return resultMap;
    }

    @Override
    public boolean respPullApplyNotice(String responseBody) {
        JSONObject jsonObject = JsonUtils.get(responseBody);
        String code = jsonObject.getString("code");
        return Eq.object(code, "0000");
    }

    @Override
    public Object reqPushApplyNotice(ApiReceiveNotice apiReceiveNotice) {
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        resultMap.put("phoneMd5", apiReceiveNotice.getPhoneMd5());
        return resultMap;
    }

    @Override
    public boolean respPushApplyNotice(String responseBody) {
        JSONObject jsonObject = JsonUtils.get(responseBody);
        String code = jsonObject.getString("code");
        return Eq.object(code, "0000");
    }


}
